package com.yuntsg.nnsfcp.controller.front;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.yuntsg.nnsfcp.common.beans.ResultBean;
import com.yuntsg.nnsfcp.common.utils.CheckUtil;
import com.yuntsg.nnsfcp.front.entity.UserInfo;
import com.yuntsg.nnsfcp.front.mapper.UserInfoMapper;
import com.yuntsg.nnsfcp.service.front.CheckService;
import com.yuntsg.nnsfcp.service.front.ut.BCryptPasswordEncoder;
import com.yuntsg.nnsfcp.service.front.ut.PinYinManyUtil;
import com.yuntsg.nnsfcp.service.front.ut.PinYinUtil;
import com.yuntsg.nnsfcp.util.Operation;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

/**
 * 后台增删改查前台用户
 *
 * @author ：ljx
 * @date ：Created in 2019/11/11
 */
//@Api(tags = "后台增删改查前台用户")
@RestController
@RequestMapping("back_edit_front_user")
public class BackEditFrontUserController {

    @Resource
    private UserInfoMapper userInfoMapper;

    @Resource
    private CheckService checkService;

    @Resource
    private HttpServletRequest request;


    /**
     * 添加用户
     *
     * @return
     */
    @PostMapping("add_user")
//    @ApiOperation(value = "后台增加一个前台用户, 直接搬前台的用户修改页 ")
    @Operation(value = "新增一个前台用户")
    public ResultBean<Object> addUser(@RequestBody UserInfo userInfo) {

        checkLogin();

        CheckUtil.notNull(userInfo, "不能添加空");
        CheckUtil.notNull(userInfo.getAccount(), "账号不能为空");
        CheckUtil.notNull(userInfo.getPassword(), "密码不能为空");
        CheckUtil.notNull(userInfo.getPassword(), "手机号不能为空");
        CheckUtil.notNull(userInfo.getEmail(), "邮件不能为空");

        //判断账户重复注册
        UserInfo checkAccountUser = userInfoMapper.selectOne(new QueryWrapper<UserInfo>().eq("account", userInfo.getAccount()));
        CheckUtil.check(checkAccountUser == null, "该账户已被使用");

        //判断手机号重复注册
        CheckUtil.check(checkService.checkIsPhone(userInfo.getPhone()), "请核对手机号");
        UserInfo checkPhoneUser = userInfoMapper.selectOne(new QueryWrapper<UserInfo>().eq("phone", userInfo.getPhone()));
        CheckUtil.check(checkPhoneUser == null, "该手机号已被使用");

        //判断邮箱重复注册
        CheckUtil.check(checkService.checkIsEmail(userInfo.getEmail()), "请输入正确的邮箱");
        UserInfo checkEmailUser = userInfoMapper.selectOne(new QueryWrapper<UserInfo>().eq("email", userInfo.getEmail()));
        CheckUtil.check(checkEmailUser == null, "该邮件已被使用");

        String encodePass = new BCryptPasswordEncoder().encode(userInfo.getPassword());
        userInfo.setPassword(encodePass);
        userInfo.setIsDelete(0);
        userInfo.setIsCheck(2);
        userInfo.setAddTime(LocalDateTime.now());
        userInfoMapper.insert(userInfo);
        return new ResultBean<>("success");
    }

    /**
     * 删除用户
     *
     * @param userId 用户id
     * @return
     */
    @GetMapping("del_user")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "userId", value = "用户id"),
//            @ApiImplicitParam(name = "flag", value = "1 是设置 0 是取消", required = true)
//    })
//    @ApiOperation(value = "删除一个前台用户")
    public ResultBean<Object> delUser(Integer userId, Integer flag) {


        checkLogin();
        CheckUtil.notNull(userId, "id为空");
        UserInfo userInfo = userInfoMapper.selectOne(new QueryWrapper<UserInfo>().eq("id", userId));
        CheckUtil.notNull(userInfo, "未知用户");

        userInfo.setIsDelete(flag);
        userInfoMapper.updateById(userInfo);
        return new ResultBean<>("success");
    }

    /**
     * 黑名单用户
     *
     * @param userId 用户id
     * @return
     */
    @GetMapping("black_user")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "userId", value = "用户id"),
//            @ApiImplicitParam(name = "flag", value = "1 是设置 0 是取消", required = true)
//
//    })
//    @ApiOperation(value = "设置一个前台黑名单用户")
    public ResultBean<Object> BlackUser(Integer userId, Integer flag) {
        checkLogin();
        CheckUtil.notNull(userId, "id为空");
        UserInfo userInfo = userInfoMapper.selectOne(new QueryWrapper<UserInfo>().eq("id", userId));
        CheckUtil.notNull(userInfo, "未知用户");
        userInfo.setIsBack(flag);
        userInfoMapper.updateById(userInfo);
        return new ResultBean<>("success");
    }

    /**
     * 黑名单用户
     *
     * @param id   用户id
     * @param flag 用户状态
     * @return
     */
    @GetMapping("check_user")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "id", value = "用户id"),
//            @ApiImplicitParam(name = "flag", value = "1 是设置 0 是取消", required = true)
//
//    })
//    @ApiOperation(value = "设置审核用户")
    public ResultBean<Object> checkUser(Integer id, Integer flag) {
        checkLogin();
        CheckUtil.notNull(id, "id为空");
        UserInfo userInfo = userInfoMapper.selectOne(new QueryWrapper<UserInfo>().eq("id", id));
        CheckUtil.notNull(userInfo, "未知用户");
        userInfo.setIsCheck(flag);
        userInfoMapper.updateById(userInfo);
        return new ResultBean<>("success");
    }


    /**
     * 修改用户
     *
     * @param userInfo 用户信息实体类
     * @return
     */
    @PostMapping("update_user")
//    @ApiOperation(value = "后台修改一个前台用户, 直接搬前台的用户修改页 密码框加上直接后台修改")
    @Operation(value = "修改前台用户")
    public ResultBean<Object> updateUser(@RequestBody UserInfo userInfo) {

        checkLogin();

        CheckUtil.notNull(userInfo.getId(), "id为空");
        CheckUtil.notNull(userInfo.getAccount(), "账户不能为空");
        CheckUtil.notNull(userInfo.getEmail(), "邮箱不能为空");
        CheckUtil.notNull(userInfo.getPhone(), "手机号不能为空");
        CheckUtil.notNull(userInfo.getPassword(), "密码不能为空");

        UserInfo dbUser = userInfoMapper.selectOne(new QueryWrapper<UserInfo>().eq("id", userInfo.getId()).eq("is_delete", 0));
        CheckUtil.notNull(dbUser, "未知用户");


        //校验修改用户手机号是否重复
        if (!dbUser.getPhone().equals(userInfo.getPhone())) {
            UserInfo checkPhone = userInfoMapper.selectOne(new QueryWrapper<UserInfo>().eq("phone", userInfo.getPhone()));
            CheckUtil.check(checkPhone == null, "该手机号已被使用");
        }

        //校验修改用户邮箱是否重复
        if (!dbUser.getEmail().equals(userInfo.getEmail())) {
            UserInfo checkEmail = userInfoMapper.selectOne(new QueryWrapper<UserInfo>().eq("email", userInfo.getEmail()));
            CheckUtil.check(checkEmail == null, "该邮箱已被使用");
        }

        //判断密码是否被修改
        // *  密文替换为*返回到前台. 前台返回来不是* 就是修改了
        if (!"*".equals(userInfo.getPassword())) {
            String encodePass = new BCryptPasswordEncoder().encode(userInfo.getPassword());
            userInfo.setPassword(encodePass);
            //清空 token 重新登录
            userInfo.setToken("");
        } else {
            userInfo.setPassword(null);
        }

        userInfo.setToken(null);
        userInfo.setIsDelete(null);
        userInfo.setAddTime(null);
        userInfoMapper.updateById(userInfo);
        return new ResultBean<>();
    }

    /**
     * 获取所有的用户
     *
     * @param page  当前页
     * @param limit 每页显示多少个
     * @return
     */
    @GetMapping("get_all")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "page", value = "当前页"),
//            @ApiImplicitParam(name = "limit", value = "每页显示多少个")
//    })
//    @ApiOperation(value = "后台获取所有前台用户, 带分页")
    public ResultBean<Object> getAllUser(Integer page, Integer limit) {

        checkLogin();

        IPage<UserInfo> userInfoPage
                = userInfoMapper.selectPage(new Page<UserInfo>(page, limit), new QueryWrapper<UserInfo>()
                .eq("is_delete", 0));
        if (userInfoPage.getRecords() != null && userInfoPage.getRecords().size() > 0) {
            List<UserInfo> records = userInfoPage.getRecords();
            for (UserInfo u : records) {
                u.setPassword("******");
                u.setToken("");
                Integer isCheck = u.getIsCheck();
                // 1 则显示待审核 2 审核通过 3 审核不通过
                if (isCheck != null && isCheck == 1) {
                    u.setIsCheckStr("待审核");
                }
                if (isCheck != null && isCheck == 2) {
                    u.setIsCheckStr("审核通过");
                }
                if (isCheck != null && isCheck == 3) {
                    u.setIsCheckStr("审核不通过");
                }
            }
            return new ResultBean<>(userInfoPage);
        }

        return new ResultBean<>(Lists.newArrayList());
    }

    /**
     * 条件查询用户
     *
     * @param name    姓名
     * @param phone   手机号
     * @param account 账号
     * @param email   邮箱
     * @param type    校内校外 类型
     * @return
     */
    @GetMapping("search_user")
//    @ApiOperation(value = "后台条件查询前台用户")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "name", value = "用户名"),
//            @ApiImplicitParam(name = "phone", value = "手机号"),
//            @ApiImplicitParam(name = "account", value = "账号"),
//            @ApiImplicitParam(name = "email", value = "邮箱"),
//            @ApiImplicitParam(name = "type", value = "0=校内,1=校外"),
//            @ApiImplicitParam(name = "dele", value = "0=正常,1=已删除"),
//            @ApiImplicitParam(name = "back", value = "0=正常,1=黑名单"),
//            @ApiImplicitParam(name = "page", value = "当前页"),
//            @ApiImplicitParam(name = "limit", value = "每页显示多少个")
//    })
    public ResultBean<Object> searchUser(String name, String phone, String account, String email, String dele, String back, String type, Integer page, Integer limit) {

        checkLogin();

        boolean pageBoo = page == null || limit == null;
        CheckUtil.check(!pageBoo, "分页数据为空");

        /*boolean boo = StringUtils.isEmpty(name) && StringUtils.isEmpty(phone)
                && StringUtils.isEmpty(phone) && StringUtils.isEmpty(account)
                && StringUtils.isEmpty(email) && StringUtils.isEmpty(type);
        CheckUtil.check(!boo, "条件不能为空");*/

        QueryWrapper<UserInfo> qw = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(name)) {
            qw.like("name", name);
        }
        if (StringUtils.isNotEmpty(phone)) {
            qw.like("phone", phone);
        }
        if (StringUtils.isNotEmpty(account)) {
            qw.like("account", account);
        }
        if (StringUtils.isNotEmpty(email)) {
            qw.like("email", email);
        }
        if (StringUtils.isNotEmpty(type)) {
            if ("0".equals(type)) {
                qw.eq("type", "注册用户");
            } else if ("1".equals(type)) {
                qw.eq("type", "注册用户");
            } else {
//                CheckUtil.check(false, "未知类型");
            }
        }
        if (StringUtils.isNotEmpty(dele)) {
            qw.eq("is_delete", Integer.valueOf(dele));
        }
        if (StringUtils.isNotEmpty(back)) {
            qw.eq("is_back", Integer.valueOf(back));
        }
        IPage<UserInfo> userInfoPage = userInfoMapper.selectPage(new Page<UserInfo>(page, limit), qw);
        if (userInfoPage.getRecords() != null && userInfoPage.getRecords().size() > 0) {
            List<UserInfo> records = userInfoPage.getRecords();
            for (UserInfo u : records) {
                u.setPassword("******");
                u.setToken("");
            }
            return new ResultBean<>(userInfoPage);
        }
        return new ResultBean<>(Lists.newArrayList());
    }

    /**
     * 中文姓名转换英文姓名
     *
     * @param str 中文姓名
     * @return
     * @throws Exception
     */
    @GetMapping("pinyin")
//    @ApiOperation(value = "中文姓名转英文")
//    @ApiImplicitParam(name = "str", value = "中文姓名")
    public ResultBean<Object> pinYin(String str) throws Exception {

        checkLogin();

        if (StringUtils.isEmpty(str)) {
            CheckUtil.check(!StringUtils.isEmpty(str), "委托人姓名不能为空");
            return new ResultBean<>("");
        }

        String[] pinYinArr = new String[0];
        str = str.replaceAll(" ", "");
        if (str.contains(",")) {
            pinYinArr = str.split(",");
        } else {
            pinYinArr = new String[]{str};
        }
        //中文名去重
        Set<String> nameSet = new LinkedHashSet<>(Arrays.asList(pinYinArr));
        //英文名去重
        Set<String> distinctSet = new LinkedHashSet<>();
        //存储最终的结果
        StringBuilder nameBuilder = new StringBuilder();
        for (String name : nameSet) {
            //判断特殊符号及数字
            if (checkService.checkName(name)) {
                //判断是不是中文
                if (PinYinUtil.isChinese(name)) {
                    if (name.length() <= 4 && name.length() > 1) {
                        nameBuilder.append(PinYinManyUtil.getManyPinY(name)).append(";");
                    } else {
                        CheckUtil.check(false, "作者名长度不合法");
                    }
                } else {
                    if (!distinctSet.contains(name.toLowerCase().trim())) {
                        distinctSet.add(name.toLowerCase().trim());
                        nameBuilder.append(name).append(";");
                    }
                }
            } else {
                CheckUtil.check(false, "请勿使用特殊符号及数字");
            }
        }
        return new ResultBean<>(nameBuilder.toString());
    }

    /**
     * 判断是否登陆
     */
    private void checkLogin() {
        HttpSession session = request.getSession();
        Object userObj = session.getAttribute("user");
        CheckUtil.notNull(userObj, "请登录");
    }

}
